package com.example.springboot.ytest.geek;

import lombok.SneakyThrows;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试类成员变量共享问题
 *
 * @author yeyi
 * @date 2021-03-26
 **/

class Test {
    public int i = 0;
    public Integer ii = 0;
//    public volatile int iv = 0;
}

public class HeapShareTest implements Runnable{

    private Test t = new Test();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        HeapShareTest run = new HeapShareTest();
        for(int i = 0 ;i < 10 ; i++) {
            threadPool.execute(run);
        }
        Thread.sleep(3000);
        threadPool.shutdown();
    }

    @SneakyThrows
    @Override
    public void run() {
        Random random = new Random();
        Thread.sleep(random.nextInt(1024));
//        t.iv++;
        t.i++;
        t.ii++;
        Thread.sleep(random.nextInt(1024));
        System.out.println(Thread.currentThread().getName()+" i: " + t.i + ", ii: " + t.ii);
//        System.out.println(Thread.currentThread().getName()+" i: " + t.i + ", ii: " + t.ii+", iv: "+t.iv);
    }
}